package com.eascs.brand.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.loanapplyoplog.LoanapplyOpLog;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.recordlog.constant.O2oLogType;
import com.eascs.admin.recordlog.servcie.O2oRecordLogService;
import com.eascs.admin.recordlog.vo.O2oRecordLogVo;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.brand.entity.O2oBrandEntity;
import com.eascs.brand.entity.O2oPartnerEntity;
import com.eascs.brand.form.O2oBranPage;
import com.eascs.brand.form.O2oPartnerForm;
import com.eascs.brand.service.O2oBrandService;
import com.eascs.brand.service.O2oPartnerService;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.crm.common.service.AcqService;
import com.eascs.file.FileTypeConstants;
import com.eascs.partner.service.JxsPartnerService;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.PaginationRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rpartner")
public class O2oPartnerRestController extends O2oBiscController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private BaseUtils baseUtils;

	@Autowired
	O2oBrandService brandService;

	@Autowired
	O2oPartnerService partnerService;
	
	@Autowired
	JxsPartnerService jxsPartnerService;

	@Autowired
	O2oRecordLogService recordService;

	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;

	@Reference
	SysOrgService sysOrgService;
	
	@Reference
	AcqService acqService;

	@Value("${web.crm.url}")
	private String crmUrl;

	/** 结算方式 */
	public static final String CLEAREFORM_TYPE = "PAR_CF_OTH";
	/** 销售模式 */
	public static final String SALESMODEL_TYPE = "PAR_SM_OTH";
	/** 贷款对象 */
	public static final String LOANOBJECT_TYPE = "PAR_LO_OTH";
	/** 凭证 */
	public static final String TRADEVOUCHER_TYPE = "PAR_TV_OTH";
	/** 担保方式 */
	public static final String GUARANTEEWAY_TYPE = "Y";

	@RequestMapping("/detail")
	public PaginationRestResult getPartnerByPage(O2oBranPage branPage) {
		String pageUrl = "/rpartner/detail";
		String brandId = branPage.getBrandId() == null ? "" : branPage.getBrandId();
		pageUrl = UrlUtil.appendUrl(pageUrl, "brandId", brandId);
		pageUrl = pageUrl + "&pageIndex=";
		branPage.setPageSize(10);
		PageResult<Object[]> pageResult = partnerService.queryPartnerEntityByPage(branPage).getModel();
		String titles[] = { "申报单号", "渠道名称", "创建时间", "负责人", "联系方式", "是否与EA有合作", "贷款对象", "融资额度(万元)", "状态" };
		Button edit = ButtonHelper.createAjaxButton(null, "/rpartner/view_edit?parameter=", "editPartner");
		Button[] Button = new Button[] { edit, null };
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, new SelectDataOption("YW"), new SelectDataOption("parLoanObject"), null, new SelectDataOption("parWFStutus") };

		/*
		Button delete = ButtonHelper.createAjaxConfirmButton("删除", "/rpartner/delete?parameter=", "editPartner");
		delete.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("-1".equals(params[9] + "") || "3".equals(params[9] + ""))
					return true;
				else
					return false;
			}
		});
		Button startFlow = ButtonHelper.createAjaxButton("发起流程", "/rpartner/startFlow?id=", "startPartnerFlow");// parameter为合作方id
		startFlow.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("-1".equals(params[9] + "") || "3".equals(params[9] + ""))
					return true;
				else
					return false;
			}
		});
		Button edit = ButtonHelper.createAjaxButton("编辑", "/rpartner/view_edit?parameter=", "editPartner");// parameter为合作方id
		edit.setShowButtonFilter(new ShowButtonFilter() {
			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				if ("-1".equals(params[9] + "") || "3".equals(params[9] + ""))
					return true;
				else
					return false;
			}
		});*/

		//Button[] titleButtons = new Button[] { edit, delete, startFlow };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles, pageUrl);
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		o2oPagingInfo.setBuildPagingNavigation(true);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setTitleButtons(Button);
		//o2oPagingInfo.setMoreButtons(titleButtons);
		o2oPagingInfo.setRendTo("#partner_detail");
		ViewContext.put("branPage", branPage);
		return PaginationRestResult.buildPaginationRestResult(o2oPagingInfo);
	}

	@RequestMapping("/recordlog")
	public PaginationRestResult getLogByPage(O2oRecordLogVo vo) {
		vo.setPageSize(10);
		String url = "/rpartner/recordlog";
		String logType = vo.getLogType() == null ? "" : vo.getLogType();
		url = UrlUtil.appendUrl(url, "logType", logType);
		url = url + "&pageIndex=";
		PageResult<Object[]> pageResult = recordService.findPartnerLogByPage(vo);
		String titles[] = { "编号", "操作人", "操作时间", "操作类型", "描述" };
		SelectDataOption[] selectDataOptions = { null, null, null, new SelectDataOption("LOGTYPE"), null };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, url);
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setBuildPagingNavigation(true);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setRendTo("#record_log");
		return PaginationRestResult.buildPaginationRestResult(paginationInfo);
	}

	@RequestMapping("/view_add")
	public BaseRestResult<String> openAdd(String brandId) {
		User user = UserHolder.getUser();
		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("currentUser", user.getCname());
		ViewContext.put("currentUserCode", user.getNo());
		ViewContext.put("brandId", brandId);
		ViewContext.put("crmUrl", crmUrl);
		return HtmlRestResult.popHtmlFragment("/brand/partner_add");
	}

	@RequestMapping("/view_flow")
	public BaseRestResult<String> viewFlow(String approvalStatus, String referId, String nodeAuditorId) {
		String approvalUrl = baseUtils.getApprovalUrl(nodeAuditorId, ProcessTemplate.PROECESS_TYPE_PARTNERS_AUDIT_BP);// 审批代办列表详情URL
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(referId);
		O2oBrandEntity brandEntity = brandService.getEntityById(o2oPartnerEntity.getBrandId());
		queryDataList(referId, FileTypeConstants.PARTNER_TYPE_RPMENT, "detail");
		String agreeUrl = baseUtils.getApprovalAgreeUrl(referId, nodeAuditorId, ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("brandEntity", brandEntity);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("parameter", referId);
		ViewContext.put("approvalStatus", approvalStatus);// 流程经办状态是待办/已办/已发起，待办状态才显示审批栏
		ViewContext.put("vo", o2oPartnerEntity);
		return HtmlRestResult.popHtmlFragment("/brand/partner_flow");
	}

	@RequestMapping("/view_detail")
	public BaseRestResult<String> detailModel(String parameter) {
		queryDataList(parameter, FileTypeConstants.PARTNER_TYPE_RPMENT, "detail");
		String agreeUrl = baseUtils.getApprovalAgreeUrl(parameter, "", ProcessTemplate.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("parameter", parameter);
		return HtmlRestResult.popHtmlFragment("/brand/partner_detail");
	}
	/**
	 * 脱敏查看弹窗
	 * @param id
	 * @return
	 */
	@RequestMapping("/show_window")
	public BaseRestResult<String> showWindow(String id) {
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(id);
		ViewContext.put("vo", o2oPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);
		return HtmlRestResult.popHtmlFragment("/brand/partner_show");
	}
	
	@RequestMapping("/updateData")
	public BaseRestResult<String> updateData() {
		logger.info("----开始处理合作方平台历史数据问题");
		List<O2oPartnerEntity> list = partnerService.getEntityList();
		logger.info("----共需处理[{}]条",list.size());
		int count = 0;
		for (O2oPartnerEntity item : list) {
			count++;
			logger.info("----正在处理第[{}]条,id:[{}],name:[{}]",count,item.getId(),item.getPartnerName());
			try {
				List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(item.getOrgProvinceId());
				if (actOrgList == null || actOrgList.size() == 0) {
					logger.info("----[找不到经办平台，请联系管理员],O2oPartnerId:[{}]",item.getId());
					continue;
				}
				ActOrgEntity actOrgEntity = null;
				for (ActOrgEntity org : actOrgList) {
					if(org.getOrgLevel() == 4)
						actOrgEntity = org;
				}
				if (actOrgEntity == null) {
					logger.info("----[找不到经办平台对应的省区金融部，请联系管理员],O2oPartnerId:[{}]",item.getId());
					continue;
				}
				item.setOrgId(actOrgEntity.getUnitNo());
				item.setOrgName(actOrgEntity.getOrgName());
				ModelResult<Boolean> update = partnerService.update(item);
				if (update.isSuccess() && !update.getModel()) {
					logger.info("----合作方平台历史数据更新失败,O2oPartnerId:[{}]",item.getId());
				}
			} catch (Exception e) {
				logger.info("----合作方平台历史数据问题异常,err:[{}]",e);
			}
		}
		logger.info("----结束处理合作方平台历史数据问题");
		return  BaseRestResult.info("处理成功");
	}
	
	
	@RequestMapping("/add")
	public BaseRestResult<String> add(O2oPartnerForm form) {
		ModelResult<Boolean> checkUp = checkUp(form);
		if (!checkUp.getModel()) {
			return BaseRestResult.warn(checkUp.getErrMsg());
		}
		String [] arr = form.getOrgProvinceId().split("_");
		form.setOrgProvinceId(arr[0]);
		form.setOrgProvince(arr[1]);
		O2oPartnerEntity entity = new O2oPartnerEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setUpdateTime(new Date());
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(entity.getOrgProvinceId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if(org.getOrgLevel() == 4)
				actOrgEntity = org;
		}
		if (actOrgEntity == null) {
			return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
		}
		entity.setOrgProvince(entity.getOrgProvince());
		entity.setOrgId(actOrgEntity.getUnitNo());
		entity.setOrgName(actOrgEntity.getOrgName());
		entity.setIsShare(form.getIsShare());

		boolean result = partnerService.getEntityByNameAndCode(entity.getPartnerName(), entity.getPartnerCode());
		if (!result) {
			return BaseRestResult.warn("该合作方已存在");
		}
		ModelResult<Boolean> insertResult = partnerService.insert(entity);
		if (insertResult.isSuccess() && !insertResult.getModel()) {
			return BaseRestResult.warn(insertResult.getErrMsg());
		}
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_APT, entity.getBrandId(), "新增品牌合作方信息");
		partnerService.saveEntityLog(log);
		ViewContext.put("crmUrl", crmUrl);
		ViewContext.put("vo", entity);
		return BaseRestResult.info("添加成功,请上传附件").andRedirect("/brand/detail?parameter=" + entity.getBrandId()  + "&p="+entity.getId());
	}

	@RequestMapping("/delete")
	public BaseRestResult<String> delete(String parameter) {
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(parameter);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oPartnerEntity, "delete");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}
		if (StringUtil.isEmpty(parameter)) {
			return BaseRestResult.warn("参数为空，无法删除！");
		} else {
			ModelResult<Boolean> deleteResult = partnerService.delete(parameter);
			if (deleteResult.isSuccess() && deleteResult.getModel()) {
				return BaseRestResult.info("删除成功").andRefresh();
			} else {
				return BaseRestResult.info(deleteResult.getErrMsg());
			}
		}
	}

	@RequestMapping("/view_edit")
	public BaseRestResult<String> openEdit(String parameter) {
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(parameter);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oPartnerEntity, "edit");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}

		List<ActOrgEntity> orgProvince = sysOrgService.getOrgProvince();
		ViewContext.put("ActOrgEntitys", orgProvince);
		ViewContext.put("vo", o2oPartnerEntity);
		ViewContext.put("crmUrl", crmUrl);

		O2oBrandEntity brand = brandService.queryBrandEntityById(o2oPartnerEntity.getBrandId()).getModel();
		ViewContext.put("brand", brand);
		return HtmlRestResult.popHtmlFragment("/brand/partner_edit");
	}
	
	

	@RequestMapping("/edit")
	public BaseRestResult<String> saveEdit(O2oPartnerForm form) {
		ModelResult<Boolean> checkUp = checkUp(form);
		if (!checkUp.getModel()) {
			return BaseRestResult.warn(checkUp.getErrMsg());
		}
		String [] arr = form.getOrgProvinceId().split("_");
		form.setOrgProvinceId(arr[0]);
		form.setOrgProvince(arr[1]);
		O2oPartnerEntity entity = new O2oPartnerEntity();
		BeanUtils.copyProperties(form, entity);
		entity.setUpdateTime(new Date());
		List<ActOrgEntity> actOrgList = sysOrgService.getLeafNodeByParentId(entity.getOrgProvinceId());
		if (actOrgList == null || actOrgList.size() == 0) {
			return BaseRestResult.warn("找不到经办平台，请联系管理员");
		}
		ActOrgEntity actOrgEntity = null;
		for (ActOrgEntity org : actOrgList) {
			if(org.getOrgLevel() == 4)
				actOrgEntity = org;
		}
		if (actOrgEntity == null) {
			return BaseRestResult.warn("找不到经办平台对应的省区金融部，请联系管理员");
		}
		entity.setOrgProvince(entity.getOrgProvince());
		entity.setOrgId(actOrgEntity.getUnitNo());
		entity.setOrgName(actOrgEntity.getOrgName());
		if (!form.getOldPartnerName().equals(entity.getPartnerName())) {
			boolean result = partnerService.getEntityByNameAndCode(entity.getPartnerName(), entity.getPartnerCode());
			if (!result) {
				return BaseRestResult.warn("该合作方已存在");
			}
		}
		ModelResult<Boolean> update = partnerService.update(entity);
		if (update.isSuccess() && !update.getModel()) {
			return BaseRestResult.warn(update.getErrMsg());
		}
		LoanapplyOpLog log = getEntity(UserHolder.getUser().getCname(), O2oLogType.PARTNER_UPDATE_APT, entity.getBrandId(), "修改品牌合作方信息");
		partnerService.saveEntityLog(log);
		return BaseRestResult.info("修改成功").andRedirect(UrlHelper.build("/partner/index"));
	}

	@RequestMapping("startFlow")
	public BaseRestResult<String> startFlow(String id) {
		ModelResult<Boolean> checkAttachment = partnerService.checkAttachment(id);
		if (!checkAttachment.isSuccess() || !checkAttachment.getModel() ) {
			return BaseRestResult.warn(checkAttachment.getErrMsg());
		}
		O2oPartnerEntity o2oPartnerEntity = partnerService.getEntityById(id);
		ModelResult<Boolean> checkRole = isCurrentRole(o2oPartnerEntity, "startFlow");
		if (!checkRole.getModel()) {
			return BaseRestResult.warn(checkRole.getErrMsg());
		}
		ModelResult<Boolean> startUp = partnerService.startUp(id);
		if (startUp.isSuccess() && startUp.getModel()) {
			return BaseRestResult.info("流程启动成功").andRedirect(UrlHelper.build("/partner/index"));
		} else {
			return BaseRestResult.warn(startUp.getErrMsg());
		}
	}
	
	
	
	
	
	
	public O2oPartnerEntity formToEntity(O2oPartnerEntity entity, User user) {
		O2oPartnerEntity o2oPartnerEntity = new O2oPartnerEntity();
		o2oPartnerEntity.setBrandId(entity.getBrandId());
		o2oPartnerEntity.setOperator(user.getCname());
		o2oPartnerEntity.setOperatorId(user.getNo());
		o2oPartnerEntity.setPartnerCode(entity.getPartnerCode());
		o2oPartnerEntity.setPartnerName(entity.getPartnerName());
		o2oPartnerEntity.setUpdateTime(new Date());
		return o2oPartnerEntity;
	}
	


	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称联想合作方信息
	 *               </p>
	 * @author CXW and LMX
	 * @date 2016年11月21日 下午4:26:28
	 * @version V1.0
	 */
	@RequestMapping(value = "/referrer")
	public BaseRestResult<List<Object[]>> getPartnerByName(String partnerName,String loanType) {
		List<Object[]> data = new ArrayList<>();
		User user = UserHolder.getUser();// 登录用户
		if (StringUtil.hasText(partnerName)) {
			data = acqService.queryAcq(partnerName, loanType, user).getModel();
//			data = partnerService.getPartnerByName(partnerName);
		}
		return BaseRestResult.buildRestResult(data);
	}

	/**
	 * 局部加载上传附件
	 * 
	 * @param parameter
	 * @return
	 */
	@RequestMapping("/loadfile")
	public HtmlRestResult querySQBZJFile(String parameter) {
		queryDataList(parameter, FileTypeConstants.PARTNER_TYPE_RPMENT, null);
		queryDataListPicture(parameter, FileTypeConstants.PARTNER_TYPE_PICTURE, null);
		queryDataListEvidence(parameter, FileTypeConstants.PARTNER_TYPE_EVIDENCE, null);
		ViewContext.put("parameter", parameter);
		return HtmlRestResult.html("/brand/parterfile");
	}

	public void queryDataList(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	public void queryDataListPicture(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultPicture", paginationInfo);// 个人附件
	}
	public void queryDataListEvidence(String loanapplyNo, String code, String detailFlag) {
		PageResult<Object[]> pageResult = o2oLoanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null, ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		if (!"detail".equals(detailFlag)) {
			AjaxConfirmButton[] dealButton = null;
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
			paginationInfo.setMoreButtons(dealButton);
		}
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultEvidence", paginationInfo);// 个人附件
	}

	public ModelResult<Boolean> checkUp(O2oPartnerForm entity) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		// Pattern p =
		// Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		// Matcher m = p.matcher(entity.getParMobile());
		// boolean matchesResult = m.matches();
		// if (!matchesResult) {
		// modelResult.setErrMsg("联系电话格式不正确");
		// modelResult.setModel(false);
		// return modelResult;
		// }
		if (CLEAREFORM_TYPE.equals(entity.getCleareForm()) && StringUtils.isEmpty(entity.getCleareFormDes())) {
			modelResult.setErrMsg("请填写结算方式");
			modelResult.setModel(false);
			return modelResult;
		}
		if (SALESMODEL_TYPE.equals(entity.getSalesModel()) && StringUtils.isEmpty(entity.getSalesModelDes())) {
			modelResult.setErrMsg("请填写销售模式");
			modelResult.setModel(false);
			return modelResult;
		}
		if (LOANOBJECT_TYPE.equals(entity.getLoanObject()) && StringUtils.isEmpty(entity.getLoanObjectDes())) {
			modelResult.setErrMsg("请填写贷款对象");
			modelResult.setModel(false);
			return modelResult;
		}
		if (entity.getTradeVoucher().indexOf(TRADEVOUCHER_TYPE) != -1 && StringUtils.isEmpty(entity.getTradeVoucherDes())) {
			modelResult.setErrMsg("请填写交易凭证");
			modelResult.setModel(false);
			return modelResult;
		}
		if (GUARANTEEWAY_TYPE.equals(entity.getGuaranteeWay()) && StringUtils.isEmpty(entity.getGuaranteeDes())) {
			modelResult.setErrMsg("请填写担保方式");
			modelResult.setModel(false);
			return modelResult;
		}
		if (!GUARANTEEWAY_TYPE.equals(entity.getIsSignAgreement()) && StringUtils.isEmpty(entity.getSignAgreementDes())) {
			modelResult.setErrMsg("是否签署回购协议字段填写错误");
			modelResult.setModel(false);
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;
	}

	public ModelResult<Boolean> isCurrentRole(O2oPartnerEntity entity, String operateType) {
		ModelResult<Boolean> modelResult = new ModelResult<>();
		User user = UserHolder.getUser();
		if (!user.getNo().equals(entity.getOperatorId()) && !user.isSuperAdministrator()) {
			if ("edit".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人编辑");
			} else if ("delete".equals(operateType)) {
				modelResult.setErrMsg("该信息只能由经办人删除");
			} else if ("startFlow".equals(operateType)) {
				modelResult.setErrMsg("该流程只能由经办人发起");
			}
			modelResult.setModel(false);
			return modelResult;
		}
		modelResult.setModel(true);
		return modelResult;

	}

	/**
	 * @Description:
	 * 				<p>
	 *               根据渠道名称联想佣金推荐方(合作方)
	 *               </p>
	 * @author CXW
	 * @date 2016年11月21日 下午4:26:28
	 * @version V1.0
	 */
	@RequestMapping(value = "/commice")
	public BaseRestResult<List<Object[]>> getPartnerName(String commiceRecommend) {
		List<Object[]> data = new ArrayList<>();
		if (StringUtil.hasText(commiceRecommend)) {
			List<Object[]> platform = new ArrayList<>();
			platform = sysOrgService.getOrgListLikeName(commiceRecommend, ActOrgEntity.ORG_LEVEL_PLATFORM, UserHolder.getUser()).getModel();
			if (platform.size() > 0) {
				for (int i = 0; i < platform.size(); i++) {
					data.add(platform.get(i));
				}
			}
			data.addAll(partnerService.getPartnerName(commiceRecommend));
		}
		return BaseRestResult.buildRestResult(data);
	}
}
